﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Yxinmt.Controls;
using Yxinmt.Interface;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace Yxinmt.Windows.Meeting
{
	public class FileReader2
	{
		WebView2 _WebView { get; set; }
        Entity.FileInfo _FileInfo { get; set; }
		string _ServiceUrl { get; set; }

        Dictionary<string, object> _AxFramerOptions { get; set; }

        public Controls.AxFramerControl _AxFramerControl { get; set; }

        Controls.WindowsFormsHost _WindowsFormsHost { get; set; }

        List<string> _OfficeTypes { get; set; }

        static List<FileReader2> _FileReader2List { get; set; }

        IWindow _Window { get; set; }

        static FileReader2()
        {
            _FileReader2List = new List<FileReader2>();
        }

        public FileReader2(IWindow win, Controls.WebView2 webView, Controls.WindowsFormsHost windowsFormsHost, string serviceUrl)
		{
            _FileNameDict = new Dictionary<string, string>();

            _AxFramerOptions = new Dictionary<string, object>();
            _AxFramerOptions.Add("Name", "AxFramerControl"+ Guid.NewGuid().ToString().Replace("-", string.Empty));

            _OfficeTypes = new List<string>() { ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx" };

            _Window = win;
            _FileReader2List.Add(this);

            _WindowsFormsHost = windowsFormsHost;
            _WebView= webView;
            _ServiceUrl= serviceUrl;
        }

        Dictionary<string,string> _FileNameDict { get; set; }

        public static void Dispose()
        {
            _FileReader2List.ForEach(f => f.DisposeFile());
        }

        public void Activate()
        {
            if (_WindowsFormsHost.IsVisible && _AxFramerControl != null)
            {
                _AxFramerControl.FramerControl.Activate();
                _AxFramerControl.FramerControl.Refresh();
                _AxFramerControl.FramerControl.Update();
            }
        }

        void DisposeFile()
        {
            try
            {
                if (_AxFramerControl != null)
                {
                    _AxFramerControl.FramerControl.Close();
                    _AxFramerControl.FramerControl.Dispose();
                    _AxFramerControl.FramerControl = null;
                    _AxFramerControl = null;

                    foreach (var kvp in _FileNameDict)
                    {
                        if (File.Exists(kvp.Value)) File.Delete(kvp.Value);
                    }
                }
            }
            catch { }
        }

        public bool IsOffice { get; set; }

        public void OpenFile(Guid meetingId, Entity.FileInfo file, Action<string> callback, Action<string> progress)
        {
            _FileInfo = file;
            UploadDownload.DownloadFile(meetingId, file, (p) =>
           {
               if(_IsClosed) return;
               Task.Run(() =>
               {
                   _Window.Window.Dispatcher.Invoke(() =>
                   {
                       if (p.Percentage == 100)
                       {
                           Thread.Sleep(200);
                           progress("文件正在加载中……");
                       }
                       else
                       {
                           string size1 = Utility.Common.GetFileSize(p.SentBytes);
                           string size2 = Utility.Common.GetFileSize(p.TotalBytes);
                           string message = $"文件正在下载中，已下载：{size1}/{size2}，下载进度：{p.Percentage}%";
                           progress(message);
                       }
                   });
               });

           }, (filePath) =>
           {
               if (_IsClosed) return;
               if (string.IsNullOrEmpty(filePath) && string.IsNullOrEmpty(file.Message)) return;
               IsOffice = _OfficeTypes.Contains(file.FileType);
               Task.Run(() =>
               {
                   try
                   {
                       _Window.Window.Dispatcher.Invoke(() =>
                       {
                           if (!string.IsNullOrEmpty(file.Message))
                           {
                               callback(file.Message);
                               return;
                           }

                           if (IsOffice) officeFileOpen(filePath);
                           else webOpen(filePath);
                           callback(file.Message);
                       });
                   }
                   catch (Exception ex)
                   {
                       ex = Utility.Common.GetInnerException(ex);
                       Utility.LoggerProxy.Exception("FileReader2", "OpenFile", ex);
                       _Window.Window.Dispatcher.Invoke(() =>
                      {
                          callback(ex.Message);
                      });
                   }
               });
           });
        }

        public void ShowToolBars()
        {
            if (_AxFramerControl != null)
            {
                _AxFramerControl.SetToolbars();
            }
        }

        public void ShowLoading()
        {
            string url = AppDomain.CurrentDomain.BaseDirectory + "html\\loading.html";
            _WebView.SetValue(url);
            _WebView.SetVisible(true);
        }

        void officeFileOpen(string fileName)
        {
            fileName = Utils.CopyFile(_FileNameDict, fileName);
            //Close();
            initAxFramerControl();
            try
            {
                _AxFramerControl.OpenFile(fileName, true);
                _WebView.SetVisible(false);
                _WindowsFormsHost.SetVisible(true);
            }
            catch (Exception ex)
            {
                ex = Utility.Common.GetInnerException(ex);
                throw ex;
            }
        }

        void initAxFramerControl()
        {
            try
            {
                _AxFramerControl = new Controls.AxFramerControl(_AxFramerOptions, _WindowsFormsHost);
                _AxFramerControl.InitAxFramerControl(_WindowsFormsHost.WpfWindowsFormsHost);
                _AxFramerControl.FramerControl.OnFileCommand += FramerControl_OnFileCommand;
                //_AxFramerControl.FramerControl.Toolbars = false;
                _AxFramerControl.FramerControl.set_EnableFileCommand(DSOFramer.dsoFileCommandType.dsoFileSave, false);
                _AxFramerControl.FramerControl.set_EnableFileCommand(DSOFramer.dsoFileCommandType.dsoFileSaveAs, false);
            }
            catch (Exception ex)
            {
                throw new Exception("初始化dsoframer.ocx失败：" + ex.Message + "，请手动注册dsoframer.ocx！");
            }
        }

        private void FramerControl_OnFileCommand(object sender, AxDSOFramer._DFramerCtlEvents_OnFileCommandEvent e)
        {
            switch (e.item)
            {
                case DSOFramer.dsoFileCommandType.dsoFileSave:
                    e.cancel = true;
                    _Window.Alert("文件只读");
                    break;
                case DSOFramer.dsoFileCommandType.dsoFileSaveAs:
                    _Window.Alert("文件只读");
                    e.cancel = true;
                    break;
            }
        }

        void webOpen(string fileUrl)
        {
            _WebView.SetValue(fileUrl);
            _WindowsFormsHost.SetChid(null);
            _WindowsFormsHost.SetVisible(false);
            _WebView.SetVisible(true);
        }


        public bool _IsClosed { get; set; }
        public void Close()
        {
            _IsClosed = true;
            if (_WindowsFormsHost.IsVisible && _AxFramerControl != null)
            {
                _WindowsFormsHost.SetChid(null);
                _WindowsFormsHost.SetVisible(false);
                _AxFramerControl.Close();
                _AxFramerControl.FramerControl = null;
                _AxFramerControl = null;
            }
            if (_WebView.IsVisible)
            {
                _WebView.SetValue(null);
                _WebView.SetVisible(false);
            }
        }
    }
}

